package apis

import (
	"github.com/gin-gonic/gin"
	"tylnmall/models"
	"github.com/jinzhu/gorm"
	"common/logger"
	"net/http"
	"tylnmall/constant"
	"errors"
	"math"
	"fmt"
	"tylnmall/service"
	"strings"
)

func UserListApi(c *gin.Context) {
	type param struct {
		Page int `json:"page" form:"page"`
	}
	var p param
	var users []*models.User
	var err error
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	var count float64
	if err := db.Model(&models.User{}).Count(&count).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	if p.Page == 0 {
		p.Page = 1
	} else if float64(p.Page) > math.Ceil(count/8.0) {
		p.Page = 1
	}
	if err = db.Limit(8).Offset((p.Page - 1) * 8).Find(&users).Error; err != nil {
		logger.Error(err)
		err = errors.New("user not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"list": users, "pageNum": math.Ceil(count / 8.0), "userNum": count})
}

func UserListByIdApi(c *gin.Context) {
	type param struct {
		Id int `json:"id" form:"id"`
	}
	var users []*models.User
	var err error
	var p param
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Where("id = ?", p.Id).Find(&users).Error; err != nil {
		logger.Error(err)
		err = errors.New("user not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"user": users})
}

//获取商铺权限的用户
func UserForStoryApi(c *gin.Context) {
	type param struct {
		Type int `json:"type" form:"type"` //0.用户类别不为0的用户;1.用户类别不为0且没有商铺的用户
	}
	var p param
	var err error
	var User []*models.User
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if p.Type > 1 {
		p.Type = 0
	}
	db := c.MustGet("ty").(*gorm.DB)
	dbExc := db.Where("type < 2")
	if p.Type == 0 {
		if err = dbExc.Find(&User).Error; err != nil {
			err = errors.New("user not found")
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		c.JSON(http.StatusOK, gin.H{"list": &User})
		return
	} else if p.Type == 1 {
		var story []*models.Story
		var list []int
		if err = db.Order("user_owner_id").Find(&story).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		for index, s := range story {
			if index > 0 {
				if s.UserOwnerId == story[index-1].UserOwnerId {
					fmt.Println(s.UserOwnerId)
					fmt.Println(index - 1)
					fmt.Println(story[index-1].UserOwnerId)
					continue
				}
			}
			list = append(list, s.UserOwnerId)
		}
		if err = dbExc.Where("id not in (?)", list).Find(&User).Error; err != nil {
			err = errors.New("user not found")
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		c.JSON(http.StatusOK, gin.H{"list": &User})
		return
	}
}

func UserUpdateImgApi(c *gin.Context) {
	type param struct {
		Id  int    `json:"id" form:"id"`
		Url string `json:"url" form:"url"`
	}
	var p param
	var err error
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	b, u := service.IsUser(db, p.Id)
	fmt.Println(u)
	if !b {
		err = errors.New("user not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorNotUser, "err_msg": constant.TranslateErrCode(constant.ErrorNotUser)})
		return
	}
	u.Image = p.Url
	if err = db.Save(&u).Error; err != nil {
		logger.Error(err)
		err = errors.New("user not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"user": u, "status": "success"})
}

//修改用户信息
func UserUpdateApi(c *gin.Context) {
	var err error
	var User models.User
	if err = c.Bind(&User); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	fmt.Println(User)
	db := c.MustGet("ty").(*gorm.DB)
	b, user := service.IsUser(db, User.Id)
	if !b {
		err = errors.New("user not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorNotUser, "err_msg": constant.TranslateErrCode(constant.ErrorNotUser)})
		return
	}
	fmt.Println(user)
	if User.Name != "" {
		user.Name = User.Name
	}
	if User.Phone != "" {
		user.Phone = User.Phone
	}
	if User.Address != "" {
		user.Address = User.Address
	}
	if User.Username != "" {
		user.Username = User.Username
	}
	if User.Password != "" {
		user.Password = User.Password
	}
	if User.Type <= 2 && User.Type >= 0 {
		user.Type = User.Type
	}
	//else {
	//	err = errors.New("user not found")
	//	logger.Error(err)
	//	c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
	//	return
	//}
	fmt.Println(user)
	if err = db.Save(&user).Error; err != nil {
		logger.Error(err)
		err = errors.New("user not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"user": user, "status": "success"})
}

//添加用户
func UserAddApi(c *gin.Context) {
	var err error
	var User models.User
	var errMsg string
	if err = c.Bind(&User); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if User.Name == "" {
		errMsg += " name is error"
	}
	if User.Phone == "" || len(User.Phone) > 11 {
		errMsg += " phone is error"
	}
	if User.Address == "" {
		errMsg += " address is error"
	}
	if User.Username == "" {
		errMsg += " username is error"
	}
	if User.Password == "" {
		errMsg += "password is error"
	}
	if User.Type > 2 || User.Type < 0 {
		errMsg += "type is error"
	}
	if User.Image == "" {
		errMsg += "image is error"
	}
	if errMsg != "" {
		err = errors.New(errMsg)
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	var user []*models.User
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Where("username = ?", User.Username).Find(&user).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	if len(user) == 0 {
		if err = db.Create(&User).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
	} else {
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorUserName, "err_msg": constant.TranslateErrCode(constant.ErrorUserName)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

//删除用户
func UserDelApi(c *gin.Context) {
	type param struct {
		Id int `json:"id" form:"id"`
	}
	var p param
	var err error
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	b, user := service.IsUser(db, p.Id)
	if !b {
		err = errors.New("user not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorNotUser, "err_msg": constant.TranslateErrCode(constant.ErrorNotUser)})
		return
	}
	if err = db.Delete(&user).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	b, user = service.IsUser(db, p.Id)
	if b {
		c.JSON(http.StatusOK, gin.H{"status": "fail"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

//批量删除用户
func UserDelListApi(c *gin.Context) {
	type param struct {
		Ids string `json:"ids" form:"ids"`
	}
	var p param
	var err error
	var user models.User
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	var list []string
	list = strings.Split(p.Ids, ",")
	fmt.Println(list)
	if len(list) <= 0 {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Where("id in (?)", list).Delete(&user).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

//关注用户
func UserCollectionAddApi(c *gin.Context) {
	type param struct {
		UserId           int `json:"user_id" form:"user_id"`
		CollectionUserId int `json:"collection_user_id" form:"collection_user_id"`
	}
	var p param
	var err error
	var user models.User
	var Collection []*models.UserCollection
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Where("id = ?", p.CollectionUserId).First(&user).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if err = db.Where("user_id = ? and collection_user_id = ?", p.UserId, p.CollectionUserId).Find(&Collection).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if len(Collection) > 0 {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	var collection models.UserCollection
	collection.UserId = p.UserId
	collection.CollectionUserId = p.CollectionUserId
	if err = db.Create(&collection).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

//取消用户关注
func UserCollectionDelApi(c *gin.Context) {
	type param struct {
		UserId           int `json:"user_id" form:"user_id"`
		CollectionUserId int `json:"collection_user_id" form:"collection_user_id"`
	}
	var p param
	var err error
	var collection models.UserCollection
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Where("user_id = ? and collection_user_id = ?", p.UserId, p.CollectionUserId).First(&collection).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if err = db.Delete(&collection).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

//查询用户收藏的用户列表
func UserCollectionUserListApi(c *gin.Context) {
	type param struct {
		Id    int `json:"id" form:"id"`       //userId
		Limit int `json:"limit" form:"limit"` //每页数量
		Page  int `json:"page" form:"page"`   //页码
	}
	var p param
	var err error
	var count float64
	var user models.User
	var collection []*models.UserCollection
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if p.Limit <= 0 {
		p.Limit = 10
	}
	if p.Page <= 0 {
		p.Page = 1
	}
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Where("id = ?", p.Id).First(&user).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if err = db.Limit(p.Limit).Offset((p.Page - 1) * p.Limit).Where("user_id = ?", p.Id).Find(&collection).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if err := db.Where("user_id = ?", p.Id).Model(&models.UserCollection{}).Count(&count).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	type list struct {
		Id              int     `json:"id"`
		Name            string  `json:"name"`
		Image           string  `json:"image"`
		CountPost       float64 `json:"count_post"`
		CountCollection float64 `json:"count_collection"`
		CountBack       float64 `json:"count_back"`
	}
	var List []*list
	for _, col := range collection {
		var u models.User
		if err = db.Where("id = ?", col.CollectionUserId).First(&u).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
			return
		}
		var l list
		//该用户发帖数量
		if err := db.Where("user_id = ?", u.Id).Model(&models.Post{}).Count(&l.CountPost).Error; err != nil {
			logger.Error(err)
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		//该用户收藏的帖子数量
		if err := db.Where("user_id = ?", u.Id).Model(&models.Collection{}).Count(&l.CountCollection).Error; err != nil {
			logger.Error(err)
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		//该用户回复数量
		if err := db.Where("user_id = ?", u.Id).Model(&models.Backpost{}).Count(&l.CountBack).Error; err != nil {
			logger.Error(err)
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}

		l.Id = u.Id
		l.Image = u.Image
		l.Name = u.Name
		List = append(List, &l)
	}
	c.JSON(http.StatusOK, gin.H{"List": &List, "count": count})

}

//查询用户发帖信息
func UserMesApi(c *gin.Context) {
	type param struct {
		Id     int `json:"id" form:"id"` //userId
		UserId int `json:"user_id" form:"user_id"`
	}
	var p param
	var err error
	var user models.User
	var count_post float64
	var count_collection float64
	var count_back float64
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Where("id = ?", p.Id).First(&user).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if err = db.Where("id = ?", p.Id).First(&user).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}

	//该用户发帖数量
	if err := db.Where("user_id = ?", p.Id).Model(&models.Post{}).Count(&count_post).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	//该用户收藏的帖子数量
	if err := db.Where("user_id = ?", p.Id).Model(&models.Collection{}).Count(&count_collection).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	//该用户回复数量
	if err := db.Where("user_id = ?", p.Id).Model(&models.Backpost{}).Count(&count_back).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	var coll []*models.UserCollection
	if err = db.Where("user_id = ? and collection_user_id = ?", p.UserId, p.Id).Find(&coll).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	IsUserCollect := 0
	if len(coll) > 0 {
		IsUserCollect = 1
	}
	c.JSON(http.StatusOK, gin.H{"name": user.Name, "image": user.Image, "post": count_post, "collection": count_collection, "back": count_back, "is_user_collect": IsUserCollect})
}
